from datetime import date, timedelta

# count = User.objects.filter(last_login__gte=今天的0点).count()
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.users.models import User


class UserDailyActiveCountView(APIView):
    # 添加权限为 管理员认证
    # permission_classes = [IsAdminUser]

    def get(self, request):
        # 1 获取当前日期
        today = date.today()
        # 2 获取用户总数
        count = User.objects.filter(last_login__gte=today).count()
        # 3 返回数据

        return Response({"count": count, 'date': today})
        # 4 登录权限验证


class UserDailyOrderCountView(APIView):

    def get(self, request):
        # 1 获取当前日期
        today = date.today()
        # 2 获取下单用户数量
        # User.objects.filter(用户的订单的创建时间 >= 今天0点).count()
        count = User.objects.filter(orderinfo__create_time__gte=today).count()
        # 3 返回数据
        return Response({"count": count, 'date': today})


class UserMonthCountView(APIView):

    def get(self, request):
        # 1获取到一个月（30天）前的日期
        start_data = date.today() - timedelta(days=30)  # 5.30

        print(start_data)

        date_ls = []
        # 2 遍历30次 获取每一天的用户注册数量
        for i in range(30):
            # User.objects.filter(date_joined >= 昨天0点 and 注册时间 < 今天0点).count()
            current_date = start_data + timedelta(days=i)  # 当前循环到的日期 0点
            next_date = start_data + timedelta(days=i + 1)  # 当前循环到的日期的下一天的0点
            count = User.objects.filter(date_joined__gte=current_date,
                                        date_joined__lt=next_date).count()  # 5.30
            date_ls.append({
                "count": count,
                "date": current_date
            })
        # 3结果放到列表里
        # 4返回数据
        return Response(date_ls)


# 每天增加的用户数量
# statistical/day_increment/
class UserdayincrementView(APIView):

    def get(self, request):
        # 1 获取当前日期
        today = date.today()
        # 2 获取用户总数
        count = User.objects.filter(date_joined__gte=today).count()
        # 3 返回数据

        return Response({"count": count, 'date': today})
        # 4 登录权限验证

# statistical/total_count/
# 所有用户的数量
class UsertotalcountView(APIView):

    def get(self, request):
        # 1 获取当前日期
        today = date.today()
        # 2 获取用户总数
        count = User.objects.filter().count()
        # 3 返回数据

        return Response({"count": count, 'date': today})
        # 4 登录权限验证

